package android.preference;

import de.Ox539.nagroid.TimeRange;
import de.schoar.nagroid.DM;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class TimeRangePreference extends DialogPreference {
	final class TimeChangedListener implements OnTimeChangedListener {
		final private TimePicker tpStart, tpEnd;
		private boolean enabled = false;
		
		TimeChangedListener(TimePicker tpStart, TimePicker tpEnd) {
			tpStart.setOnTimeChangedListener(this);
			tpEnd.setOnTimeChangedListener(this);
			this.tpStart = tpStart;
			this.tpEnd = tpEnd;
			
			tpStart.setCurrentHour(range.getStartHour());
			tpStart.setCurrentMinute(range.getStartMinute());
			tpEnd.setCurrentHour(range.getEndHour());
			tpEnd.setCurrentMinute(range.getEndMinute());
			
			enabled = true;
		}
		
		@Override
		public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
			if(!this.enabled)
				return;

			if(view == this.tpStart) {
				range.setStartHour(hourOfDay);
				range.setStartMinute(minute);
			} else if(view == this.tpEnd) {
				range.setEndHour(hourOfDay);
				range.setEndMinute(minute);
			} else {
				throw new RuntimeException("Invalid state.");
			}
		}
		
		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}
	}
		
	private TimeRange range = new TimeRange();
	@SuppressWarnings("unused")
	private TimeChangedListener listener;
	
	public TimeRangePreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		setPersistent(true);
		restoreValue();
	}

	public TimeRangePreference(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		setPersistent(true);
		restoreValue();
	}
	
	@Override
	public View onCreateDialogView() {
		final LinearLayout layout = new LinearLayout(getContext());
		layout.setOrientation(LinearLayout.VERTICAL);
		
		TimePicker tpStart = new TimePicker(getContext());
		tpStart.setIs24HourView(true);
		TimePicker tpEnd = new TimePicker(getContext());
		tpEnd.setIs24HourView(true);

		listener = new TimeChangedListener(tpStart, tpEnd);

		final TextView untilLabel = new TextView(getContext());
		untilLabel.setText("until");
		untilLabel.setGravity(Gravity.CENTER);
		
		layout.addView(tpStart);
		layout.addView(untilLabel);
		layout.addView(tpEnd);
		
		return layout;
	}

	protected void saveValue() {
		// XXX: This should use persistString instead.
		DM.I.getConfiguration().setNotificationTimeSwitchRange(range);
	}
	
	protected void restoreValue() {
		// XXX: This should use getPersistedString instead.
		range = DM.I.getConfiguration().getNotificationTimeSwitchRange();
	}
	
	@Override
	protected void onDialogClosed(boolean positiveResult) {
		if(positiveResult)
			saveValue();
	}
}